import { defineStore } from 'pinia'

export const useOrderStore = defineStore('order', {
  state: () => ({
    orders: [],
    currentOrder: null,
    cart: []
  }),
  
  actions: {
    // 添加商品到购物车
    addToCart(item) {
      const existingItem = this.cart.find(i => i.id === item.id)
      if (existingItem) {
        existingItem.quantity++
      } else {
        this.cart.push({ ...item, quantity: 1 })
      }
    },
    
    // 从购物车移除商品
    removeFromCart(itemId) {
      const index = this.cart.findIndex(item => item.id === itemId)
      if (index > -1) {
        this.cart.splice(index, 1)
      }
    },
    
    // 清空购物车
    clearCart() {
      this.cart = []
    },
    
    // 创建订单
    createOrder() {
      const order = {
        id: Date.now().toString(),
        items: [...this.cart],
        total: this.cart.reduce((sum, item) => sum + item.price * item.quantity, 0),
        status: 'pending',
        createTime: new Date().toISOString()
      }
      this.orders.push(order)
      this.currentOrder = order
      this.clearCart()
      return order
    },
    
    // 更新订单状态
    updateOrderStatus(orderId, status) {
      const order = this.orders.find(o => o.id === orderId)
      if (order) {
        order.status = status
      }
    },
    
    // 删除订单
    deleteOrder(orderId) {
      const index = this.orders.findIndex(o => o.id === orderId)
      if (index > -1) {
        this.orders.splice(index, 1)
      }
    }
  },
  
  getters: {
    cartTotal: (state) => {
      return state.cart.reduce((sum, item) => sum + item.price * item.quantity, 0)
    },
    
    cartCount: (state) => {
      return state.cart.reduce((sum, item) => sum + item.quantity, 0)
    }
  }
}) 